<!--
    出库订单列表组件
-->
<template>
    <div>
        <div class="e-m-t-45 flex" style="justify-content: space-between">
            <div class="e-flex-1">
                <el-button @click="downloadwithdrawa()" style="margin-bottom:30px; margin-top: 1px;" type="primary"
                    plain><i class="iconfont icon-excel"></i>导出Excel</el-button>
                <!-- <el-button type="primary" icon="el-icon-plus" plain @click="create">新建出库单</el-button> -->
            </div>
            <div class="flex">
                <!-- <div class="e-flex-1">
                    <el-button type="primary" icon="el-icon-plus" plain @click="create">新建出库单</el-button>
                </div> -->
                <el-form :inline="true" class="demo-form-inline">
                    <el-form-item label="">
                        <el-input placeholder="关键字搜索" v-model="key" prefix-icon="el-icon-search"></el-input>
                    </el-form-item>
                    <!-- <el-form-item>
                        <span class="other-search-show" :class="isActive ? 'is-active' : ''" @click="isActive = !isActive">
                            {{ isActive ? '收起筛选' : '更多筛选' }}<i class="el-icon-arrow-down el-icon--right"></i>
                        </span>
                    </el-form-item> -->
                    <el-form-item>
                        <el-button type="primary" @click="getList(true)">查询</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>

        <!-- 更多筛选条件 -->
		<div class="other-search-form" :class="isActive ? 'is-active' : ''">
			<el-form class="e-flex-1" label-position="left" label-width="auto" :inline="true" size="small">
                <div class="flex align-items-center">
					<!-- 时间筛选 -->
					<timeChangeList v-model="timeType" @input="getList" @change="changeTime"></timeChangeList>
				</div>
                <div class="flex align-items-center">
                    <div class="e-flex-1" v-if="franchiseId == null">
                        <el-form-item label="所属加盟商">
                            <franchiseList v-model="innerFranchiseId" :firstSelect="true" @change="selectFranchise"></franchiseList>
                        </el-form-item>
                    </div>
                    <div class="e-flex-1" v-if="storeId == null && resetFilter">
                        <el-form-item label="出库站点">
                            <storeList ref="storeList" v-model="innerStoreid" :franchiseId="innerFranchiseId" :multiple="true" @change="selectStore"></storeList>
                        </el-form-item>
                    </div>
                    <div class="e-flex-1" v-if="innerFranchiseId > 0 && resetFilter">
                        <el-form-item label="出库厂商">
                            <manufacturerList ref="manufacturerList" v-model="manufacturerId" :franchiseId="innerFranchiseId" @change="selectManufacturer"></manufacturerList>
                        </el-form-item>
                    </div>
                </div>
			</el-form>
		</div>

        <div class="type-state e-m-b-30">
            <span v-for="(item, index) in statusArr" :key="index" :class="{ 'on': state == item.value }"
                @click="state = item.value">{{ item.name }}</span>
        </div>

        <!-- 自定义表格 -->
        <custom-table :table-data="tableData" :columns="tableColumns" :actions="tableActions" :total="total"
            :page-index="pageIndex" :page-size="pageSize" :show-summary="true" :summary-method="getSummaries"
            @page-change="handlePagination" @action-click="handleTableAction">
            <template #franchise="scope">
                <span v-if="scope.row.franchise.id > 0">{{ scope.row.franchise.name }}</span>
            </template>
            <template #staff="scope">
                <span v-if="scope.row.staff.id > 0">{{ scope.row.staff.name }}</span>
                <!-- <span v-if="scope.row.packinorder.packid > 0">{{ scope.row.packinorder.brothername }}(打包站)</span> -->
            </template>
            <template #manufacturer="scope">
                <span v-if="scope.row.manufacturer">{{ scope.row.manufacturer.name }}</span>
                <span v-if="scope.row.packinorder">{{ scope.row.packinorder.packname }}(打包站)</span>
            </template>
            <!-- 自定义状态 -->
            <template #state="scope">
                <span class="color-success" v-if="scope.row.state == '已完结'">{{ scope.row.state }}</span>
                <span class="color-warning" v-else-if="scope.row.state == '已出库'">{{ scope.row.state }}</span>
                <span class="color-danger" v-else>{{ scope.row.state }}</span>
            </template>
        </custom-table>

        <!-- 详情页面弹窗(线上用户订单) -->
        <el-drawer :visible.sync="viewShow.show" direction="rtl" size="80%" :with-header="false">
            <storeOrderViews v-if="viewShow.show" :id="viewShow.id" @goBack="viewShow.show = false"></storeOrderViews>
        </el-drawer>
    </div>
</template>

<script>
import manufacturerList from '@/components/form-select-type/manufacturerList.vue'
import franchiseList from '@/components/form-select-type/franchiseList.vue'
import storeOrderViews from '/pages/order/store/components/storeOrderViews.vue'
import timeChangeList from '@/components/form-select-type/timeChangeList.vue'
import storeList from '@/components/form-select-type/storeList.vue'
export default {
    name: 'storeOutOrderList',
    props: {
        franchiseId: {
            type: [Number, String],
            default: null
        },
        storeId:{
            type: Number,
            default: null
        }
    },
    components: {
        storeOrderViews,
        timeChangeList,
        storeList,
        franchiseList,
        manufacturerList
    },
    data() {
        return {
            isActive: true,
            viewShow: {
                id: 0,
                show: false //详情页面弹窗
            },
            // 时间类型
            timeType: 0, //筛选时间类别：0全部，1今日，2昨日，3本月，4上月，5本季度，6上季度，7本年，9自定义时间段
            startDate: '', //开始时间
            endDate: '', //结束时间
            loading: true,
            statusArr: [
                {
                    name: '全部',
                    value: null
                },
                {
                    name: '已出库',
                    value: 1
                },
                {
                    name: '已完结',
                    value: 2
                },
                {
                    name: '已取消',
                    value: 3
                }
            ],
            state: null,
            innerFranchiseId: null,
            key: '',
            pageIndex: 1,
            pageSize: 10,
            total: 0,
            tableData: [],
            tableColumns: [
                {
                    prop: 'number',
                    label: '订单编号',
                    width: 'auto'
                },
                {
                    prop: 'store',
                    label: '出库站点',
                    formatter: row => `${row.store ? row.store.name : '--'}`
                },
                {
                    prop: 'manufacturer',
                    label: '运输至厂商（打包站）',
                    slotName: 'manufacturer'
                },
                {
                    prop: 'franchise',
                    label: '所属加盟商',
                    slotName: 'franchise'
                },
                {
                    prop: 'weight',
                    label: '出库重量（KG）',
                    sortable: true
                },
                {
                    prop: 'sellweight',
                    label: '出库重量（回）',
                    sortable: true
                },
                {
                    prop: 'quantity',
                    label: '出库数量（件）',
                    sortable: true
                },
                {
                    prop: 'sellquantity',
                    label: '出库数量（回）',
                    sortable: true
                },
                {
                    prop: 'amount',
                    label: '预估出库总额（元）',
                    sortable: true
                },
                {
                    prop: 'sellamount',
                    label: '实际出库总额（元）',
                    sortable: true
                },
                {
                    prop: 'staff',
                    label: '负责人',
                    width: 180,
                    slotName: 'staff'
                },
                {
                    prop: 'createddatetime',
                    label: '出库时间',
                    width: 180
                },
                {
                    prop: 'endtime',
                    label: '结单时间',
                    width: 180,
                    formatter: row => `${row.state == '已出库' ? '--' : row.endtime}`
                },
                {
                    prop: 'state',
                    label: '订单状态',
                    slotName: 'state',
                },
                {
                    prop: 'remarks',
                    label: '备注',
                    formatter: row => `${row.remarks ? row.remarks : '--'}`
                }
            ],
            tableActions: [
                {
                    name: 'view',
                    label: '查看'
                }
            ],
            options: [{
                value: null,
                label: '全部'
            }, {
                value: 0,
                label: '待出库'
            },
            {
                value: 1,
                label: '已装车'
            }, {
                value: 2,
                label: '已出库'
            }, {
                value: 3,
                label: '已完结'
            },
            {
                value: 4,
                label: '已取消'
            }
            ],
            param: {},
            innerStoreid: [],
            resetFilter: true
        }
    },
    mounted() {
        for (let k in this.$route.query) {
            if (this.$route.query[k]) {
                if (k == 'pageIndex' || k == 'pageSize' || k == 'packStationId') {
                    this[k] = parseInt(this.$route.query[k])
                } else if (k == 'startDate' || k == 'endDate') {
                    this[k] = this.$route.query[k]
                    this.value1 = [this.$route.query['startDate'], this.$route.query['endDate']]
                    this.timeType = 9
                } else {
                    this[k] = this.$route.query[k]
                }
            }
        }

        if(this.franchiseId > 0){
            this.innerFranchiseId = this.franchiseId
        }
        this.getList()
    },
    watch: {
        state(value) {
            this.pageIndex = 1
            this.getList()
        }
    },
    methods: {
        getList(renew = true) {
            if (renew == true) {
                this.pageIndex = 1
            }
            if(!this.innerFranchiseId){
                return
            }
            this.tableData = []
            this.loading = true
            this.param = {
                "pageIndex": this.pageIndex,
                "pageSize": this.pageSize,
                "key": this.key,
                "state": this.state,
                "startDate": this.startDate,
                "endDate": this.endDate,
                "timeType": this.timeType,
                "franchiseId": this.innerFranchiseId || 0
                // "storeIds": [this.innerStoreid]
            }
            if(this.storeId > 0){
                this.param.storeIds = [this.storeId]
            }else{
                this.param.storeIds = this.innerStoreid
            }
            
            return this.$axios.post('/Store/OutOrder/List', this.param).then((res) => {
                this.loading = false
                this.tableData = res.rows;
                this.total = res.total;
            }).catch((err) => {
                this.loading = false
            })
        },
        // 选择加盟商
        selectFranchise(value){
            this.resetFilter = false
            this.innerFranchiseId = value
            this.innerStoreid = []
            this.manufacturerId = null
            this.getList(true).finally(() => {
                this.resetFilter = true
            })
        },
        // 选择站点
        selectStore(value){
            this.innerStoreid = value,
            this.getList(true)
        },
        // 选择厂商
        selectManufacturer(value){
            this.manufacturerId = value
            this.getList(true)
        },
        // 翻页操作处理
        handlePagination({ pageIndex, pageSize }) {
            this.pageIndex = pageIndex
            this.pageSize = pageSize
            this.getList(false) // 获取新数据
        },
        // 操作按钮点击事件
        handleTableAction({ action, row, event }) {
            switch (action) {
                case 'view':
                    this.goView(event, row)
                    break
            }
        },
        getSummaries(param) {
            // 合计
            const { columns, data } = param;
            const sums = [];
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = '合计';
                    return;
                }
                const values = data.map(item => Number(item[column.property]));
                if (!values.every(value => isNaN(value))) {
                    sums[index] = values.reduce((prev, curr) => {
                        const value = Number(curr);
                        if (!isNaN(value)) {
                            return prev + curr;
                        } else {
                            return prev;
                        }
                    }, 0);
                    sums[index] += '';
                } else {
                    sums[index] = '';
                }

                if (column.label == '总额（元）') {
                    sums[index] = Number(sums[index]).toFixed(2)
                }
                else if (column.label == '重量（KG）') {
                    sums[index] = Number(sums[index]).toFixed(2)
                } else if (column.label == '数量（件）') {
                    sums[index] = Number(sums[index]).toFixed(2)
                } else {
                    sums[index] = ''
                }
            });

            return sums;
        },
        downloadwithdrawa() {
            let request = {
                "pageIndex": this.pageIndex,
                "pageSize": this.pageSize,
                "key": this.key,
                "state": this.state,
                "startDate": this.startDate,
                "endDate": this.endDate,
                "timeType": this.timeType,
                "franchiseId": this.innerFranchiseId || 0
            }
            if(this.storeId > 0){
                requeststoreIds = [this.storeId]
            }else{
                request.storeIds = this.innerStoreid
            }
            this.$axios.post('/Store/OutOrder/Download', {
                "downloadfilename": '出库单',
                request,
                "fields": [
                    {
                        "e": "Number",
                        "c": "订单编号"
                    },
                    {
                        "e": "store.name",
                        "c": "出库站点"
                    },
                    {
                        "e": "manufacturer.name || packinorder.packname",
                        "c": "运输至厂商（打包站）"
                    },
                    {
                        "e": "franchise.name",
                        "c": "所属加盟商"
                    },
                    {
                        "e": "weight",
                        "c": "出库重量(KG)"
                    },
                    {
                        "e": "sellweight",
                        "c": "出库重量(回)"
                    },
                    {
                        "e": "quantity",
                        "c": "出库数量(件)"
                    },
                    {
                        "e": "sellquantity",
                        "c": "出库数量(回)"
                    },
                    {
                        "e": "amount",
                        "c": "预估出库总额(元)"
                    },
                    {
                        "e": "sellamount",
                        "c": "实际出库总额(元)"
                    },
                    {
                        "e": "staff.name",
                        "c": "负责人"
                    },
                    {
                        "e": "endtime",
                        "c": "出库时间"
                    },
                    {
                        "e": "state",
                        "c": "订单状态"
                    },
                    {
                        "e": "remarks",
                        "c": "备注"
                    },
                ]
            }, {
                responseType: 'blob'
            }).then(res => {
                console.log(res)
                let content = res;
                let fileName = '出库单.xls'
                this.utils.saveAndExport(content, fileName)
            })
        },
        changeTime(e) {
            console.log(e)
            this.startDate = e['startDate']
            this.endDate = e['endDate']
            this.timeType = e['timeType']
            this.getList()
        },
        clearstate(v) {
            this.getList();
        },
        create() {
            this.$router.push({
                path: '/order/store/create'
            })
        },
        
        goView(event, row) {
            if (event.ctrlKey) {
                console.log('Ctrl + 左键点击');
                // 这里可以执行你需要的操作
                let param = []
                for (let k in this.param) {
                    if (this.param[k]) {
                        param.push(`${k}=${this.param[k]}`)
                    }
                }
                this.$router.push(`/order/store/list?${param.join('&')}`)
                window.open('/order/store/Views?id=' + row.id, '_blank');
            } else {
                console.log('普通点击');
                this.viewShow.id = row.id
                this.viewShow.show = true
            }
        },
        rowClick(row) {
            this.viewShow.id = row.id
            this.viewShow.show = true
        }
    }
}
</script>

<style lang="scss" scoped>
.nav-bar {
    padding: 20px 0 0;
}

.send {
    margin-top: 15px;
    margin-right: 10px;
}

.dialogForm {
    display: flex;
    flex-wrap: wrap;

    .el-form-item {
        width: 50%;
        float: left;

        &.all {
            width: 100%;
        }

        .el-select {
            width: 100%;
        }
    }
}
.other-search-show {
	cursor: pointer;

	&.is-active {
		color: var(--main)
	}

	&.is-active .el-icon-arrow-down {
		transform: rotate(180deg);
	}

	.el-icon-arrow-down {
		transition: all 0.3s;
	}
}
.other-search-form {
	overflow: hidden;
	height: 0;
	transition: all 0.3s;
	border-color: transparent;

	&.is-active {
		height: auto;
		padding: 18px;
		background: var(--light);
		border: 1px solid var(--border-light);
		padding-bottom: 0px;
		margin-bottom: 18px;
		border-radius: 4px;
		box-sizing: border-box;
	}
}
</style>